package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.model.entity.Contract;
import com.wing.common.model.entity.ContractChangeRecord;
import com.wing.common.model.request.ContractChangeRecordForm;
import com.wing.common.model.request.ContractForm;
import com.wing.common.model.response.ContractChangeRecordVO;
import com.wing.common.model.response.ContractVO;
import com.wing.common.service.ContractChangeRecordService;
import com.wing.common.service.ContractService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.contract.model.entity.ContractCategory;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-供应商合同管理", tags = "#/purchase/supplierContract")
@RestController("supplierContractController")
@RequestMapping("purchase/admin/supplierContract")
@RequiredArgsConstructor
public class SupplierContractController {

    private final ContractService contractService;
    private final ContractChangeRecordService contractChangeRecordService;

    @ApiOperation(value = "查询所有供应商合同", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "code", value = "编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ContractVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long contractCategoryId
            ,String companyName
            ,String code
            ,String contactName
            ,String startCreateTime
            ,String endCreateTime
            ,String status
            ,Long id
            ,Long subjectId
    ){
        Page<ContractVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        //搜索
        if(null != contractCategoryId){
            params.put("contractCategoryId", contractCategoryId);
        }
        if(StringUtils.isNotBlank(companyName)){
            params.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(code)) {
            params.put("code", code);
        }
        if(StringUtils.isNotBlank(contactName)){
            params.put("contactName", contactName);
        }
        if(StringUtils.isNotBlank(startCreateTime)){
            params.put("startCreateTime", startCreateTime);
        }
        if(StringUtils.isNotBlank(endCreateTime)){
            params.put("endCreateTime", endCreateTime);
        }

        if(StringUtils.isNotBlank(status)){
            params.put("status", status);
        }
        if (null != id) {
            params.put("id", id);
        }
        if(null != subjectId){
            params.put("subjectId", subjectId);
        }
        params.put("type", ContractCategory.Type.supplier.getValue());

        Page<ContractVO> list = contractService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加供应商合同", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ContractForm.Add.class) ContractForm contractForm) {
        if (contractService.add(contractForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改供应商合同", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ContractForm.Update.class) ContractForm contractForm) {
        Contract contract = contractService.getById(contractForm.getId());
        if(contract == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(Contract.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(contractForm, contract, copyOptions);
        if (contractService.updateById(contract)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除供应商合同", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "contractId", value = "供应商合同id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long contractId) {
        if (contractService.removeById(contractId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询供应商合同变更记录", notes = "变更记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/contractChangeRecordList")
    public PageResult<ContractChangeRecordVO> contractChangeRecordList(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long contractId
            ,String code
    ){
        Page<ContractChangeRecordVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }

        //搜索
        if (null != contractId) {
            params.put("contractId", contractId);
        }
        if(StringUtils.isNotBlank(code)){
            params.put("code", code);
        }
        params.put("type", ContractCategory.Type.supplier.getValue());

        Page<ContractChangeRecordVO> list = contractChangeRecordService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加供应商合同变更记录", notes = "变更记录")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addContractChangeRecord")
    public JsonResult addContractChangeRecord(@Validated(ContractChangeRecordForm.Add.class) ContractChangeRecordForm contractChangeRecordForm) {
        if (contractChangeRecordService.add(contractChangeRecordForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "修改供应商合同变更记录", notes = "变更记录")
    @PutMapping("/updateContractChangeRecord")
    public JsonResult updateContractChangeRecord(@Validated(ContractChangeRecordForm.Update.class) ContractChangeRecordForm contractChangeRecordForm) {
        ContractChangeRecord contractChangeRecord = contractChangeRecordService.getById(contractChangeRecordForm.getId());
        if(contractChangeRecord == null){
            return JsonResult.fail("修改失败！");
        }
        if(contractChangeRecord.getStatus().equals(ContractChangeRecord.Status.fail)){
            contractChangeRecordForm.setStatus(ContractChangeRecord.Status.stayAudit);
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ContractChangeRecord.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(contractChangeRecordForm, contractChangeRecord, copyOptions);
        if (contractChangeRecordService.updateById(contractChangeRecord)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "是否显示添加变更记录按钮", notes = "变更记录")
    @GetMapping("/isShowAddBtn")
    public JsonResult isShowAddBtn(Long id) {
        // 不是审核通过的记录数
        int count = contractChangeRecordService.count(new QueryWrapper<ContractChangeRecord>().eq("contract_id", id).ne("status", ContractChangeRecord.Status.success));
        // 按钮的显示条件 只存在审核通过的记录
        return JsonResult.success("操作成功", count == 0);
    }

    @ApiOperation(value = "审核", notes = "变更记录")
    @PostMapping("/auditContractChangeRecord")
    public JsonResult auditContractChangeRecord(Long id, String auditOpinion, ContractChangeRecord.Status status) {
        ContractChangeRecord contractChangeRecord = contractChangeRecordService.getById(id);
        if(null == contractChangeRecord){
            JsonResult.fail("操作失败！");
        }
        contractChangeRecord.setAuditOpinion(auditOpinion);
        contractChangeRecord.setStatus(status);
        if(contractChangeRecordService.updateById(contractChangeRecord)){
            return JsonResult.success("操作成功");
        }
        return JsonResult.fail("操作失败");
    }

    @ApiOperation(value = "设置合同为终版", notes = "变更记录")
    @PostMapping("/setContractFinal")
    public JsonResult setContractFinal(Long id, String deliveryTime, String address, Long keeper) {
        try {
            if(contractChangeRecordService.setContractFinal(id, deliveryTime, address, keeper)){
                return JsonResult.success("操作成功");
            }
            return JsonResult.fail("操作失败");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }

}
